package com.whcoding.encrypt.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.whcoding.encrypt.annotation.Encrypt;
import com.whcoding.encrypt.entity.RespBeanVO;
import com.whcoding.encrypt.util.AESUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @program: spring-boot-learning
 * @description: 加密
 * @author: whcoding
 * @create: 2022-06-16 11:38
 **/
@EnableConfigurationProperties(EncryptProperties.class)
//全局增强controller
@ControllerAdvice
public class EncryptResponse implements ResponseBodyAdvice<RespBeanVO> {
	private ObjectMapper om = new ObjectMapper();

	@Autowired
	EncryptProperties encryptProperties;

	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		//判断注解信息是否为 Encrypt加密操作
		return returnType.hasMethodAnnotation(Encrypt.class);
	}

	/**
	 *
	 * @param body 原本controller要返回的信息
	 * @param returnType
	 * @param selectedContentType
	 * @param selectedConverterType
	 * @param request
	 * @param response
	 * @return
	 */
	@Override
	public RespBeanVO beforeBodyWrite(RespBeanVO body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
		//1.获取加密的key
		byte[] keyBytes = encryptProperties.getKey().getBytes();
		try {
			//2.对返回值Msg进行加密操作
			if (body.getMsg() != null) {
				body.setMsg(AESUtils.encrypt(body.getMsg().getBytes(), keyBytes));
			}
			//3.对返回值Obj进行加密操作
			if (body.getObj() != null) {
				body.setObj(AESUtils.encrypt(om.writeValueAsBytes(body.getObj()), keyBytes));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return body;
	}
}